package com.shuke.my_test.easyPoi.service;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.annotation.Excel;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.poi.excel.ExcelUtil;
import com.shuke.my_test.easyPoi.domain.UserDTO;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;

import java.util.*;

/**
 * @author 舒克、舒克
 * @date 2025/7/3 11:13
 * @description
 */
@Service
public class UserService {

    private static final String[] FIELDS = {"address","age"};

    // 导出User 信息
    public void exportUser(HttpServletResponse response) {
        List<UserDTO> list = new ArrayList<>();
        UserDTO userDTO = new UserDTO();
        UserDTO.Person boy = new UserDTO.Person();
        boy.setName("张三");
        boy.setAge(18);
        boy.setAddress("中国");
        UserDTO.Person girl = new UserDTO.Person();
        girl.setName("张三");
        girl.setAge(18);
        girl.setAddress("中国");
        userDTO.setBoy(boy);
        userDTO.setGirl(girl);


        list.add(userDTO);
        // 2. 配置导出参数
        ExportParams params = new ExportParams("用户列表", "用户数据");

//        List<ExcelExportEntity> entityList = buildDynamicColumns(UserDTO.class, FIELDS);


        // 3. 生成工作簿并写入响应流
        try (Workbook workbook = ExcelExportUtil.exportExcel(params, UserDTO.class, list)) {

            Row headerRow = workbook.getSheetAt(0).getRow(1); // 组标题行（"男生"、"女生"）
            Row headerRow2 = workbook.getSheetAt(0).getRow(2); // 字段标题行（"姓名"、"年龄"、"地址"）

// 1. 获取Person类的导出字段数量（动态计算列范围）
            int personFieldCount = UserDTO.Person.class.getDeclaredFields().length;

// 2. 遍历组标题行
            for (int colIdx = 0; colIdx < headerRow.getLastCellNum(); colIdx++) {
                Cell groupCell = headerRow.getCell(colIdx, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);

                // 3. 只处理"女生"分组
                if (groupCell != null && "女生".equals(groupCell.getStringCellValue())) {
                    int startCol = colIdx;
                    int endCol = startCol + personFieldCount - 1; // 计算女生组的列范围

                    // 4. 在女生组范围内查找年龄列
                    for (int fieldCol = startCol; fieldCol <= endCol; fieldCol++) {
                        Cell fieldCell = headerRow2.getCell(fieldCol, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);

                        if (fieldCell != null && "年龄".equals(fieldCell.getStringCellValue())) {
                            // 5. 隐藏年龄列并退出当前组查找
                            workbook.getSheetAt(0).setColumnHidden(fieldCol, true);
                            break; // 找到后立即退出内层循环
                        }
                    }
                    break; // 找到女生组后退出外层循环（假设只有一个"女生"分组）
                }
            }
            response.setHeader("Content-Disposition", "attachment;filename=users.xlsx");
            FileOutputStream fos = new FileOutputStream("G:\\tmp\\user7.xlsx");
            workbook.write(fos);
            workbook.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static List<ExcelExportEntity> buildDynamicColumns(Class<?> clz, String[] fieldNames) {
        List<ExcelExportEntity> entityList = new ArrayList<>();
        Field[] fields = clz.getDeclaredFields();

        Map<String, Boolean> hiddenMap = new HashMap<>();
        for (String fieldName : fieldNames) {
            hiddenMap.put(fieldName, true);
        }

        for (Field field : fields) {
            Excel excelAnno = field.getAnnotation(Excel.class);
            if (excelAnno != null) {
                ExcelExportEntity entity = new ExcelExportEntity(excelAnno.name(), field.getName());
                entity.setWidth(excelAnno.width());
                entity.setOrderNum(Integer.parseInt(excelAnno.orderNum()));
                // 如果hiddenMap中指定了该字段，则覆盖注解的隐藏设置
                if ( hiddenMap.containsKey(field.getName())) {
                    entity.setColumnHidden(hiddenMap.get(field.getName()));
                }
                entityList.add(entity);
            }
        }
        // 按orderNum排序
        entityList.sort(Comparator.comparingInt(ExcelExportEntity::getOrderNum));
        return entityList;
    }


}
